package LeetCode;

import java.util.Arrays;

//
// Created by ✎﹏ℳ๓独赏☆独醉 on 2024/5/29.
//
//https://leetcode.cn/problems/merge-sorted-array/description/
public class 合并两个有序数组 {
    public static void main(String[] args) {
        int[] nums1 = {3,4,5,0,0,0};
        int[] nums2 = {1,2,6};
        merge(nums1,3,nums2,3);
        System.out.println(Arrays.toString(nums1));
    }
    public static void merge(int[] nums1, int m, int[] nums2, int n) {
        if(m == 0){
            System.arraycopy(nums2,0,nums1,0,nums2.length);
            return;
        }
        if(n == 0){
            return;
        }
        if(nums2[0] > nums1[m-1]){
            System.arraycopy(nums2,0,nums1,m,n);
            return;
        }
        if(nums1[0] > nums2[n-1]){
            System.arraycopy(nums1,0,nums1,m,m);
            System.arraycopy(nums2,0,nums1,0,n);
            return;
        }
        int p1 = m-1, p2 = n-1,p = nums1.length -1;
        while (p1 >= 0 && p2 >= 0){
            if(nums1[p1] > nums2[p2]){
                nums1[p] = nums1[p1];
                p1--;
            }else {
                nums1[p] = nums2[p2];
                p2--;
            }
            p--;
        }
        while (p2 >= 0){
            nums1[p] = nums2[p2];
            p--;
            p2--;
        }
        while (p1 >= 0){
            nums1[p] = nums1[p1];
            p--;
            p1--;
        }
    }
}
